package com.mar.tech.unify.verticle;

import com.mar.tech.unify.factory.UnifyFactory;
import com.mar.tech.unify.service.database.DatabaseService;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Description: Verticle抽象 .<br>
 *
 * @author m-xy
 *     Created By 2019/12/12 10:09
 */
public abstract class BaseVerticle extends AbstractVerticle {
  private final static Logger logger = LoggerFactory.getLogger(BaseVerticle.class);
  protected DatabaseService databaseService;

  /**
   * 空句柄
   *
   * @return Vert.x 的 {@link Handler}
   */
  protected <T> Handler<AsyncResult<T>> nonHandler() {
    return non -> {
      if (non.failed()) {
        logger.error("当前操作失败", non.cause());
      }
    };
  }

  /**
   * 查询.
   *
   * @param sqlName sqlName
   * @param param   参数
   * @return Vert.x 的 {@link Future}
   */
  protected Future<JsonArray> queryFuture(String sqlName, JsonArray param) {
    Promise<JsonArray> promise = Promise.promise();
    String sql = UnifyFactory.getQuery().getString(sqlName);
    databaseService.query(sql, param, reply -> {
      if (reply.failed()) {
        promise.fail(reply.cause());
        return;
      }
      promise.complete(reply.result());
    });
    return promise.future();
  }
}
